<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
          <el-option
            v-for="dict in dict.type.anniversary_reminder_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="纪念日的名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入纪念日的名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="纪念日的日期" prop="dateNew">
        <el-date-picker clearable
                        v-model="queryParams.dateNew"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择纪念日的日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="提醒日期类型" prop="reminderDateType">
        <el-select v-model="queryParams.reminderDateType" placeholder="请选择提醒日期类型" clearable>
          <el-option
            v-for="dict in dict.type.anniversary_reminders_reminder_date_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['base:reminders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:reminders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:reminders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['base:reminders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="remindersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" prop="name" />
      <el-table-column label="类型" align="center" prop="type" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.anniversary_reminder_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="纪念日" align="center" prop="name" />
      <el-table-column label="纪念日日期" align="center" prop="dateNew" width="200">
        <template slot-scope="scope">
          <span>新历：{{ parseTime(scope.row.dateNew, '{y}-{m}-{d} {h}:{i}') }}</span><br>
          <span>农历：{{ getLunarInfo(parseTime(scope.row.dateNew, '{y}-{m}-{d}'),'')   }}</span><br>
        </template>
      </el-table-column>
      <el-table-column label="距离如今" align="center" prop="upToNowInfo" width="220">
        <template slot-scope="scope">
          <span>{{scope.row.upToNowInfo  }}</span><br>
          <span>{{scope.row.upToNowDayInfo  }}</span><br>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.anniversary_reminders_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-management"
            @click="handleSendMail(scope.row)"
            v-hasPermi="['base:reminders:send:mail']"
          >发邮件</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['base:reminders:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['base:reminders:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改纪念日提醒对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型">
                <el-option
                  v-for="dict in dict.type.anniversary_reminder_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纪念日" prop="name">
              <el-input v-model="form.name" placeholder="请输入纪念日" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纪念日（阳历）" prop="dateNew">
              <el-date-picker clearable
                              v-model="form.dateNew"
                              @change="getLunarToDate"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择纪念日（阳历）">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纪念日（阴历）" prop="dateOld">
              <el-date-picker clearable
                              v-model="form.dateOld"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择纪念日（阴历）" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提醒日期类型" prop="reminderDateType">
              <el-select v-model="form.reminderDateType" placeholder="请选择提醒日期类型">
                <el-option
                  v-for="dict in dict.type.anniversary_reminders_reminder_date_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提醒类型" prop="reminderType">
              <el-select v-model="form.reminderType" placeholder="请选择提醒类型">
                <el-option
                  v-for="dict in dict.type.anniversary_reminders_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="特定天数" prop="specialDay">
              <el-tag
                :key="tag"
                v-for="tag in specialDayTags"
                closable
                :disable-transitions="false"
                @close="handleCloseTag(tag)">
                {{tag}}
              </el-tag>
              <el-input-number
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                style="width: auto"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
              >
              </el-input-number>
              <el-button v-else class="button-new-tag" size="small" @click="showInputTag">+添加</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提前几天" prop="days">
              <el-input-number :min="1" :max="90" v-model="form.days" placeholder="请输入提前几天" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="通知方式" prop="notificationMethod">
              <el-select v-model="form.notificationMethod" placeholder="请选择通知方式">
                <el-option
                  v-for="dict in dict.type.anniversary_reminders_notification_method"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接收者信息" prop="recipient">
              <el-input v-model="form.recipient" placeholder="请输入接收者信息" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="共享用户账号" prop="sharedAccount">
              <el-input v-model="form.sharedAccount" placeholder="请输入共享用户账号" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="消息内容" prop="message">
              <el-input v-model="form.message" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="个性化背景" prop="background">
              <image-upload v-model="form.background" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReminders, getReminders, delReminders, addReminders, updateReminders } from "@/api/base/reminders";
import { getLunarInfo,getLunarToDate, getUpToNowInfo, getUpToNowDayInfo } from '@/utils/dateTool'

export default {
  name: "Reminders",
  dicts: ['anniversary_reminders_reminder_date_type', 'anniversary_reminders_notification_sent', 'anniversary_reminders_type', 'anniversary_reminders_notification_method', 'anniversary_reminders_status','anniversary_reminder_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      inputVisible: false,
      inputValue: '',
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 纪念日提醒表格数据
      remindersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openSendMail: false,
      // 定时器
      intervalId: null,
      specialDayTags: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        background: null,
        name: null,
        dateNew: null,
        type: null,
        dateOld: null,
        reminderDateType: null,
        reminderType: null,
        reminderDate: null,
        notificationMethod: null,
        notificationSent: null,
        recipient: null,
        message: null,
        sharedAccount: null,
        status: null,
        label: null,
        days: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "纪念日的名称不能为空", trigger: "blur" }
        ],
        dateNew: [
          { required: true, message: "纪念日的日期不能为空", trigger: "blur" }
        ],
        dateOld: [
          { required: true, message: "纪念日的日期不能为空", trigger: "blur" }
        ],
        reminderDateType: [
          { required: true, message: "提醒日期类型不能为空", trigger: "change" }
        ],
        reminderType: [
          { required: true, message: "提醒类型不能为空", trigger: "change" }
        ],
        reminderDate: [
          { required: true, message: "提醒日期不能为空", trigger: "blur" }
        ],
        notificationMethod: [
          { required: true, message: "通知方式不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    // 每分钟调用一次
    this.intervalId = setInterval(() => {
      this.updateReminders();
    }, 5000);
  },
  methods: {
    /** 查询纪念日提醒列表 */
    getList() {
      this.loading = true;
      listReminders(this.queryParams).then(response => {
        this.remindersList = response.rows;
        this.total = response.total;
        this.remindersList.forEach(reminder => {
          reminder.upToNowInfo = getUpToNowInfo(reminder.dateNew,'');
          reminder.remark = getUpToNowInfo(reminder.dateNew,'');
          reminder.upToNowDayInfo = getUpToNowDayInfo(reminder.dateNew,'');
        });
        this.loading = false;
      });
    },
    /** 定时刷新距离时间*/
    updateReminders(){
      this.remindersList.forEach(reminder => {
        reminder.upToNowInfo = getUpToNowInfo(reminder.dateNew,'');
        reminder.upToNowDayInfo = getUpToNowDayInfo(reminder.dateNew,'');
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        background: null,
        name: null,
        type: null,
        dateNew: null,
        dateOld: null,
        reminderDateType: null,
        reminderType: null,
        reminderDate: null,
        notificationMethod: null,
        notificationSent: null,
        recipient: null,
        message: null,
        sharedAccount: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null,
        status: null,
        label: null,
        days: null,
        specialDay: null,
      };
      this.resetForm("form");
      this.formMail = {
        name: null,
        dateNew: null,
        recipient: null,
        message: null,

      };
      this.resetForm("formMail");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加纪念日提醒";
    },
    /** 新增发邮件按钮操作 */
    handleSendMail(){
      this.reset();
      this.openSendMail = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getReminders(id).then(response => {
        this.form = response.data;
        console.log("this.form",this.form)
        console.log("response.data",response.data)
        if( this.form.specialDay != null){
          this.specialDayTags = this.form.specialDay.split(';');
        }
        this.open = true;
        this.title = "修改纪念日提醒";
      });
    },

    /** 提交按钮 */
    submitForm() {
      console.log("this.form.specialDayTags",this.specialDayTags)
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理数据
          this.form.specialDay = this.specialDayTags.join(';');
          if (this.form.id != null) {
            updateReminders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReminders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除纪念日提醒编号为"' + ids + '"的数据项？').then(function() {
        return delReminders(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/reminders/export', {
        ...this.queryParams
      }, `纪念日信息导出_${new Date().getTime()}.xlsx`)
    },
    /** 获取农历*/
    getLunarInfo(timeStr,type) {
      return getLunarInfo(timeStr ,type)
    },
    /** 获取距今时间*/
    getUpToNowInfo(timeStr) {
      return getUpToNowInfo(timeStr,'')
    },
    /** 获取距今时间*/
    getUpToNowDayInfo(timeStr) {
      return getUpToNowDayInfo(timeStr,'')
    },
    /** 获取农历日期并赋值*/
    getLunarToDate(){
      this.form.dateOld = getLunarToDate(this.form.dateNew);
    },
    handleCloseTag(tag) {
      this.specialDayTags.splice(this.specialDayTags.indexOf(tag), 1);
    },

    showInputTag() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.specialDayTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    clearInterval(this.intervalId);
  },

};
</script>
<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
